package com.example.teachdemo4;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetworkImageActivity extends AppCompatActivity {

    ImageView iv_download;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_image);

        iv_download = findViewById(R.id.iv_download);

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0x1100){
                    Bitmap bitmap = (Bitmap) msg.obj;

                    iv_download.setImageBitmap(bitmap);
                }
            }
        };
    }

    public void imageDownload(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                URL url = null;
                HttpURLConnection connection = null;
                InputStream is = null;

                Bitmap bitmap = null;
                try{
                    url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1608001369357&di=4024bde6afd73cb0755f130866292b72&imgtype=0&src=http%3A%2F%2Fimage.biaobaiju.com%2Fuploads%2F20190705%2F23%2F1562340403-CRfBloGesc.jpeg");
                    connection = (HttpURLConnection) url.openConnection();

                    is = connection.getInputStream();

                    bitmap = BitmapFactory.decodeStream(is);

                    Message message = new Message();
                    message.what = 0x1100;
                    message.obj = bitmap;

                    handler.sendMessage(message);

                }catch (Exception e){

                }
            }
        }).start();

    }
}
